using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
using System.Collections.Generic;
public class ASyncSmaple_01 {
    private static readonly Stopwatch Watch = new Stopwatch ();

    public async Task<Tuple<int,int>> StartAsync () {
        Watch.Start ();
        Console.WriteLine ("---------------ASyncSmaple_01:异步方法开始---------------");
        const string url1 = "https://blog.csdn.net";
        const string url2 = "https://blog.csdn.net/JianZuoGuang";
        //Console.ReadKey();
        //Func委托，带返回值，不传入任何参数
        var t1 = await Task.Run<int> (() => { return CountCharactersAsync (1, url1); });
        Console.WriteLine("-----------T1   Await下方----------");
        var t2 = await Task.Run<int> (() => { return CountCharactersAsync (2, url2); });
        Console.WriteLine("-----------T2   Await下方----------");

        for (int i = 0; i < 3; i++) {
            ExtraOperation (i + 1);
        }

        Console.WriteLine ("url1的字符个数为={0}", t1);
        Console.WriteLine ("url2的字符个数为={0}", t2);

        Console.WriteLine ("--------------ASyncSmaple_01:异步方法结束------------------");
        Console.WriteLine (Task.CurrentId.ToString());
        Watch.Stop();

        return Tuple.Create(t1,t2);
    }
    private static int CountCharactersAsync (int id, string address) {
        var wc = new WebClient ();
        Console.WriteLine ("开始调用ID={0}: 花费={1} ms", id, Watch.ElapsedMilliseconds);

        var result = wc.DownloadData (address);
        Console.WriteLine ("调用完成ID={0}: 花费={1} ms", id, Watch.ElapsedMilliseconds);
        return result.Length;
    }
    private static void ExtraOperation (int id) {
        var s = "";
        for (int i = 0; i < 60000; i++) {
            s += i;
        }
        Console.WriteLine ("ID={0}的拼接字符串: 花费={1} ms", id, Watch.ElapsedMilliseconds);
    }
}